package cn.joybreeze.service.impl;

import cn.joybreeze.common.bo.AdminUserDetails;
import cn.joybreeze.common.bo.UsmAdmin;
import cn.joybreeze.common.util.JWTUtils;
import cn.joybreeze.common.vo.UserVO;
import cn.joybreeze.mapper.UserMapper;
import cn.joybreeze.mapper.UserRoleMapper;
import cn.joybreeze.mapper.UsmAdminMapper;
import cn.joybreeze.model.UserDO;
import cn.joybreeze.model.UserRoleDO;
import cn.joybreeze.service.UsmAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UmsAdminServiceImpl
 * @Description
 * @Author Kjwaa
 * @Email 1135274290@qq.com
 * @Date 2021/5/13 21:16
 */
@Service
public class UmsAdminServiceImpl implements UsmAdminService {
    @Autowired
    UsmAdminMapper usmAdminMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public UsmAdmin getUsmAdminByName(String username) {
        return usmAdminMapper.getUsmAdminByName(username);
    }



    @Override
    public Boolean register(UserVO userVO) {
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userVO.getUsername());
        UserDO user = userMapper.selectOne(wrapper);
        if(user != null){
            return false;
        }
        //加入数据库
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userVO, userDO);
        userMapper.insert(userDO);
        //查数据库 获取新用户的id  这里就不用了，mybatis plus会将id自动注入到userDO
        //QueryWrapper<UserDO> wrapper2 = new QueryWrapper<>();
        //wrapper2.eq("username", userDO.getUsername());
        //UserDO userDO1 = userMapper.selectOne(wrapper);

        //分配角色
        UserRoleDO userRoleDO = new UserRoleDO();
        userRoleDO.setUserId(userDO.getId());
        //默认游客角色  这里写的是管理员到时候要改，
        // 而且用户-角色表的两个id都是字符串类型，改为整型对应另外两个表的id比较好
        userRoleDO.setRoleId(1);
        userRoleMapper.insert(userRoleDO);
        return true;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!password.equals(userDetails.getPassword())){
                throw new Exception("用户名或密码错误");
            }
            if(!userDetails.isEnabled()){
                throw new Exception("账号被禁用");
            }
            //调用Security API进行登录
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);

            Map<String, String> payload = new HashMap<>();
            payload.put("username",username);

            token = JWTUtils.getToken(payload);
//            updateLoginTimeByUsername(username);
        } catch (Exception e) {
            System.out.println("登录异常");
            e.printStackTrace();
        }
        return token;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        //获取用户信息
        UsmAdmin admin = usmAdminMapper.getUsmAdminByName(username);
        if (admin != null) {
            return new AdminUserDetails(admin);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }


}
